<template>
    <div class="apply-main">
        <div class="apply-main-box">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item prop="applyTitle" label="标题">
                    <el-input
                        v-model="form.applyTitle"
                        class="custom-input"
                        maxlength="6"
                        show-word-limit
                        :disabled="isDisabled"
                        placeholder="请填写标题"></el-input>
                </el-form-item>
                <el-form-item prop="applyImg" label="图片">
                    <!-- todo: form.img -->
                    <ImgUpload
                        ref="defaultImgRef"
                        v-model="form.applyImg"
                        :is-change="true"
                        :disabled="isDisabled"
                        accept="image/png,image/jpeg,image/jpg"
                        :currentImg="getCurrentImg(form?.applyImg)"
                        @imgStateChange="imgStateChange"
                        tip-content="图片建议尺寸828*320，支持jpg、png、jpeg" />
                </el-form-item>
                <el-form-item label="加入须知">
                    <el-input
                        v-model="form.applyRemark"
                        class="custom-input2"
                        type="textarea"
                        maxlength="500"
                        show-word-limit
                        :rows="9"
                        :disabled="isDisabled"
                        placeholder="请填写协议内容"></el-input>
                </el-form-item>
            </el-form>
            <div class="form-preview">
                <div class="form-preview-header">
                    <span>{{ form.applyTitle }}</span>
                </div>
                <div class="form-preview-main">
                    <div
                        class="form-preview-main-img"
                        :style="`background-image: url(${getCurrentImg(form?.applyImg)})`"></div>
                    <div class="form-preview-main-form">
                        <h3>请完成以下条件加入{{ distributerTitle }}</h3>
                        <div class="custom-item">
                            <div class="custom-item-icon"></div>
                            <div>手机号登录</div>
                            <div class="custom-item-button custom-item-disabled">已登录</div>
                        </div>
                        <div class="custom-item" v-if="[1, 2].includes(applyDtbor)">
                            <div class="custom-item-icon"></div>
                            <div v-if="applyDtbor == 1">
                                累计购买金额达{{ amountOrNum ? amountOrNum / 100 : amountOrNum }}元
                                <div>
                                    当前进度：<span>￥0</span>/￥{{ amountOrNum ? amountOrNum / 100 : amountOrNum }}
                                </div>
                            </div>
                            <div v-if="applyDtbor == 2">
                                累计购买{{ amountOrNum }}次
                                <div>当前进度：<span>0次</span>/{{ amountOrNum }}次</div>
                            </div>
                            <div class="custom-item-button">待完成</div>
                        </div>
                        <div class="custom-bottom">
                            <div class="custom-bottom-tip">
                                <div class="custom-checkbox"></div>
                                我已认真阅读并同意<span>《加入须知》</span>
                            </div>
                            <div class="custom-bottom-button">立即加入</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="form-footer">
            <el-button type="primary" :disabled="isDisabled" @click="saveHandler">保存</el-button>
        </div>
    </div>
</template>

<script setup>
import { onUnmounted, onMounted, computed, reactive, ref, unref } from 'vue';
import { setLayout, resetLayout } from '@/hooks/layout';
import ImgUpload from '@/components/ImageUpload.vue';
import { cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import request from '@/request/index';
import store from '@/store/index';

// const defaultImg = 'https://img-shop-dev.keyid.cn/shop-api/images/20221221/Ump5QJnM1a4f7qiL.png';
const defaultImg = location.origin + '/imgs/distribution-apply-default.png';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
const isDisabled = computed(() => {
    return !permissions.has('distribution_set:apply_edit');
});

const form = reactive({
    tab: 2,
    applyTitle: '申请分销员', // 从设置中获取
    applyImg: defaultImg,
    applyRemark: ''
});
let distributerTitle = ref('分销员');
let applyDtbor = ref(0); // 申请条件
let amountOrNum = ref(null);
const formRef = ref();
const defaultImgRef = ref(null);

const rules = reactive({
    applyTitle: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 6, message: '最长不超过6个字', trigger: 'blur' }
    ],
    applyImg: [{ required: true, trigger: 'change', message: '请设置图片' }]
});

const getCurrentImg = (val, imgSrc) => {
    if (val?.[0]?.response?.data?.url) {
        return val?.[0]?.response?.data?.url;
    }
    if (!val) {
        return imgSrc || defaultImg;
    }
    if (val === 'default') {
        return imgSrc || defaultImg;
    }
    return val;
};

const setImgSrcObject = img => {
    if (img?.[0]?.response?.data?.url) {
        return img?.[0]?.response?.data?.url;
    }
    if (!img) {
        return defaultImg;
    }
    return img;
};

const saveHandler = async () => {
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            if (defaultImgRef.value.loading) {
                return ElMessage({
                    type: 'error',
                    message: '图片正在上传中...，请稍后保存'
                });
            }
            let params = cloneDeep(form);
            params.applyImg = setImgSrcObject(params.applyImg);
            const { code } = await request('distributionSettingsSave', params);
            if (code !== 0) {
                return;
            }
            // todo:setImgSrcObject
            ElMessage({
                type: 'success',
                message: '保存成功'
            });
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
};

const imgStateChange = ({ msg }) => {
    if (['上传图片只能是jpg、png、jpeg格式！'].includes(msg)) {
        ElMessage({
            type: 'error',
            message: '上传图片只能是jpg、png、jpeg格式！'
        });
    }
    setTimeout(() => {
        validateField('applyImg');
    });
};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

const getSetting = async () => {
    const { data } = await request('distributionSettingsInfo', {
        tab: 1
    });
    const {
        distributerTitle: distributerTitleCopy,
        applyDtbor: applyDtborCopy,
        amountOrNum: amountOrNumCopy
    } = (data || {})?.info || {};
    // 获取设置的值
    distributerTitle.value = distributerTitleCopy || '分销员';
    applyDtbor.value = applyDtborCopy || 0;
    amountOrNum.value = amountOrNumCopy;

    // todo输入的值
};
const getDetail = async () => {
    const { data } = await request('distributionSettingsInfo', {
        tab: 2
    });
    const { applyTitle, applyImg, applyRemark } = (data || {})?.info || {};
    form.applyTitle = applyTitle || `申请${distributerTitle.value}`;
    form.applyImg = applyImg || defaultImg;
    form.applyRemark = applyRemark;
};

onMounted(async () => {
    setLayout('custom-apply-layout');
    await getSetting();
    await getDetail();
});
onUnmounted(() => {
    resetLayout('custom-apply-layout');
});
</script>

<style lang="scss">
.custom-apply-layout {
    min-height: calc(100vh - 260px) !important;
    max-height: calc(100vh - 260px);
    overflow-y: auto;
}
</style>
<style lang="scss" scoped>
@import './style/apply.scss';
</style>
